// 节流请求时间间隔 单位ms
import axios from 'axios';
import lark from '@/config';

// const REQUEST_DELAY = 16;

const request = axios.create({
  baseURL: lark.env.request_base_url,
  timeout: 3000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
});


class HttpClient {
  handleToken(options) {
    options.headers['Authorization'] = `Bearer ${localStorage.getItem('_hash')}`;
  }

  doRequest(parameters) {
    const defaultHeaders = {
      'Content-Type': 'application/json; charset=utf-8',
    };
    return new Promise((resolve, reject) => {
      const {params, url, data, headers} = parameters;
      const options = {
        method: parameters.method,
        url,
        headers: headers === undefined ? defaultHeaders : headers,
        params: params === undefined ? {} : params,
        data: data === undefined ? {} : data,
      };
      this.handleToken(options);
      request(options)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
    });
  }

  get(parameters) {
    parameters.method = 'GET';
    return this.doRequest(parameters);
  }

  post(parameters) {
    parameters.method = 'POST';
    return this.doRequest(parameters);
  }

  delete(parameters) {
    parameters.method = 'DELETE';
    return this.doRequest(parameters);
  }
}

export const httpClient = new HttpClient();

